package liuch.netty.session;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;

import io.netty.channel.ChannelHandlerContext;

/**
 * @author: liuchenhui
 * @create: 2019-01-16 11:33
 **/
public class NettySessionRepository {


    private static Map<String, NettySession> sessionMap = Maps.newConcurrentMap();

    public static void addSession(NettySession session) {
        String devId = session.getId();
        if (sessionMap.containsKey(devId)) {
            NettySession sessionTemp = sessionMap.get(devId);
            if (session.getSession().equals(sessionTemp.getSession())) {
                return;
            }
        }
        sessionMap.put(devId, session);
    }

    public static void removeSession(ChannelHandlerContext ctx) {
        String devId = null;
        for (Map.Entry<String, NettySession> entry : sessionMap.entrySet()) {
            devId = entry.getKey();
            NettySession session = entry.getValue();
            if (ctx.equals(session.getSession())) {
                break;
            }
        }
        if (devId != null) {
            sessionMap.remove(devId);
        }
    }

    public static boolean hasSession(String devId) {
        if (sessionMap.containsKey(devId)) {
            return true;
        }
        return false;
    }

    public static NettySession getSession(String devId) {
        return sessionMap.get(devId);
    }

    public static List<NettySession> getSession() {
        return Lists.newArrayList(sessionMap.values());
    }

    public static void close(String devId) {
//        LOGGER.info("考勤机[{}]关闭连接", devId);
        NettySession session = sessionMap.get(devId);
        if (session != null) {
            ChannelHandlerContext ctx = session.getSession();
            close(ctx);
            removeSession(ctx);
        }
    }

    public static void close(ChannelHandlerContext ctx) {
        try {
            ctx.close();
            removeSession(ctx);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendMsg(String devId, String msg) {
        NettySession session = sessionMap.get(devId);
        if (session == null) {
            System.out.println("未获取到session");
            return;
        }
        ChannelHandlerContext ctx = session.getSession();
        try {
            System.out.println("给id=" + devId + "的设备发送消息,message=" + msg);
            ctx.writeAndFlush(msg);
        } catch (Exception e) {
            e.printStackTrace();
            close(devId);
        }
    }
}
